<script lang="ts" setup>
import { MessagePlugin } from 'tdesign-vue-next'
import { LockOnIcon, SecuredIcon, UserIcon } from 'tdesign-icons-vue-next'
import { computed, reactive, ref } from 'vue'
import { post } from '@/utils/api'
import CaptchaCode from '@/components/CaptchaCode.vue'
import router from '@/router'

const formData = reactive({
  email: '',
  password: '',
  captcha: '',
  remember: 1
})
const rememberPassword = ref<boolean>(true)
const rememberChange = () => {
  formData.remember = rememberPassword.value ? 1 : 0
}
const loading = ref(false)

const captchaValue = ref('')
const getValue = (val: string) => {
  captchaValue.value = val
}
const captcha = ref<any>(null)

const rules = {
  email: [{ required: true, type: 'error', trigger: 'blur' }],
  password: [{ required: true, type: 'error', trigger: 'blur' }],
  captcha: [
    { required: true },
    {
      validator: (val: any) => {
        if (val.toString().toLowerCase() === captchaValue.value.toLowerCase()) {
          return { result: true }
        }
        captcha.value.draw()
        return { result: false, message: '验证码错误' }
      },
      trigger: 'blur'
    }
  ]
}

const emailSuffix = ['@qq.com', '@163.com', '@gmail.com', '@outlook.com']
const emailOptions = computed(() => {
  const emailPrefix = formData.email.split('@')[0]
  if (!emailPrefix) return []
  return emailSuffix.map((suffix) => emailPrefix + suffix)
})

const formRef = ref<any>(null)
const login = async () => {
  const result = await formRef.value.validate()
  if (result === true) {
    loading.value = true
    const response = await post('/api/user/login', formData)
    MessagePlugin(response.status, response.message)
    if (response.status === 'success') {
      localStorage.setItem('role', response.role)
      await router.push('/console')
    }
    if (response.status === 'error') {
      captcha.value.draw()
    }
    loading.value = false
  }
}
</script>

<template>
  <t-row class="container">
    <t-col :lg="6" :md="6" :sm="12" :xl="6" :xs="12">
      <t-card header-bordered>
        <template #header>
          <img
            alt=""
            src="../../../assets/images/author/logo_light.png"
            width="110"
            style="margin: -12px auto"
          />
        </template>

        <t-form ref="formRef" :data="formData" :rules="rules" class="form" label-align="top">
          <t-form-item label="邮箱" name="email">
            <t-auto-complete
              v-model="formData.email"
              :options="emailOptions"
              placeholder="请输入邮箱"
            >
              <template #prefix-icon>
                <UserIcon />
              </template>
            </t-auto-complete>
          </t-form-item>

          <t-form-item label="密码" name="password">
            <t-input v-model="formData.password" clearable placeholder="请输入密码" type="password">
              <template #prefix-icon>
                <lock-on-icon />
              </template>
            </t-input>
          </t-form-item>

          <t-form-item label="验证码" name="captcha">
            <t-row class="captcha_container">
              <t-input v-model="formData.captcha" class="captcha_input" placeholder="请输入验证码">
                <template #prefix-icon>
                  <SecuredIcon />
                </template>
              </t-input>
              <CaptchaCode @getCaptchaValue="getValue" ref="captcha" />
            </t-row>
          </t-form-item>

          <t-form-item>
            <t-checkbox v-model="rememberPassword" @change="rememberChange">记住密码</t-checkbox>
          </t-form-item>

          <t-form-item>
            <t-button :loading="loading" block theme="primary" @click="login">登录</t-button>
          </t-form-item>
        </t-form>

        <template #footer>
          <div class="footer">
            <t-link hover="color" content="没有账号？立即注册" href="/register" />
            <t-link hover="color" content="忘记密码？" href="/forget" />
          </div>
        </template>
      </t-card>
    </t-col>
  </t-row>
</template>

<style lang="less" scoped>
.container {
  width: 100vw;
  height: calc(100vh - 98px);
  background-color: #f5f5f5;
  background-image: url('@/assets/images/author/login-bg.png');
  background-size: cover;

  .t-col {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

    .t-card {
      width: 360px;

      .logo_container {
        display: flex;
        width: 100%;
        justify-content: center;
        align-items: center;
      }

      .captcha_container {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .captcha_input {
          width: 180px;
        }
      }
    }
    .footer {
      width: 100%;
      display: flex;
      justify-content: space-between;
      margin-top: -15px;
    }
  }
}
img {
  user-select: none;
}
</style>
